<template>
  <div class="app-container">
    <transition name="el-zoom-in-top">
      <el-form v-show="show" ref="form" :inline="true" :model="form" class="demo-form-inline">
        <el-form-item label="账号">
          <el-input v-model="form.username" placeholder="账号" clearable />
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="form.name" placeholder="名称" clearable />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="form.gender" placeholder="性别" style="width: 80px" clearable>
            <el-option label="男" value="0" />
            <el-option label="女" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker
            v-model="form.birthday"
            clearable
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="form.tel" placeholder="电话" clearable />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" placeholder="邮箱" clearable />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="form.address" placeholder="地址" clearable style="width: 300px" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="状态" style="width: 80px" clearable>
            <el-option label="正常" :value="false" />
            <el-option label="禁用" :value="true" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="handleSearch">查询</el-button>
          <el-button icon="el-icon-close" plain @click="handleClearSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </transition>
    <el-row class="g-row">
      <template>
        <el-popconfirm title="确定删除吗？" @confirm="handleDelete(selectedList)">
          <el-button slot="reference" icon="el-icon-delete" type="danger" plain :disabled="selectedList.length === 0">删除</el-button>
        </el-popconfirm>
      </template>
      <el-button icon="el-icon-plus" type="primary" plain @click="handleOpenDialog()">新填</el-button>
      <div style="float: right">
        <el-button icon="el-icon-sort" plain @click="show = !show">查询条件</el-button>
        <el-button icon="el-icon-download" plain @click="handleExportSysUser">条件导出</el-button>
        <el-button icon="el-icon-upload2" plain @click="handleImportSysUser">导入</el-button>
        <el-button icon="el-icon-refresh-left" plain @click="loadList(page.currentPage,page.size)">刷新</el-button>
      </div>
    </el-row>
    <el-row class="g-row">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        @selection-change="selectedChange"
      >
        <el-table-column fixed="left" type="selection" width="55" />
        <el-table-column type="index" width="55" />
        <el-table-column prop="username" label="账号" width="170" />
        <el-table-column prop="name" label="名称" width="150" />
        <el-table-column prop="gender" label="性别" width="100">
          <template v-slot="scope">
            <span>{{ scope.row.gender == 0?'男':'女' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="birthday" label="生日" width="170" />
        <el-table-column prop="tel" label="电话" width="170" />
        <el-table-column prop="email" label="邮箱" width="170" />
        <el-table-column prop="address" label="地址" show-overflow-tooltip />
        <el-table-column prop="status" label="是否禁用" width="100">
          <template v-slot="scope">
            <el-switch v-model="scope.row.status" @change="handleChangeStatus(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="170" />
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template v-slot="scope">
            <el-button type="text" class="g-button" @click="handleOpenDialog(scope.row)">修改</el-button>
            <el-popconfirm title="确定删除吗？" @confirm="handleDelete(scope.row)">
              <el-button slot="reference" type="text" class="g-button">删除</el-button>
            </el-popconfirm>
            <el-dropdown @command="(command) => handleCommand(command, scope.row)">
              <span style="font-size: 12px" class="el-dropdown-link">更多</span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="handleResetPassword">重置密码</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row class="g-row">
      <el-pagination
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :page-size="page.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-row>

    <el-dialog
      :title="dialog.title"
      :visible.sync="dialog.visible"
      width="35%"
      :before-close="handleCloseDialog"
    >
      <el-alert
        style="margin-bottom: 20px"
        title="密码默认值为：123456，如需修改自己密码请自行到个人中心修改！"
        type="info"
        show-icon
        :closable="false"
      />
      <el-form ref="dialogForm" :rules="rules" :model="dialogForm" label-width="80px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="dialogForm.username" placeholder="请输入账号" clearable />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="dialogForm.name" placeholder="请输入名称" clearable />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio v-model="dialogForm.gender" :label="0">男</el-radio>
          <el-radio v-model="dialogForm.gender" :label="1">女</el-radio>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker
            v-model="dialogForm.birthday"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="是否禁用">
          <el-switch v-model="dialogForm.status" />
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select
            v-model="dialogForm.roles"
            multiple
            value-key="id"
            placeholder="请选择角色"
          >
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.name"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="dialogForm.tel" placeholder="请输入电话" clearable />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="dialogForm.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="dialogForm.address" type="textarea" placeholder="请输入地址" clearable />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseDialog">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import UserApi from '@/api/system/user.js'
import RoleApi from '@/api/system/role.js'
import { getToken } from '@/utils/auth'
import { upload } from '@/utils/upload'

export default {
  name: 'User',
  data() {
    return {
      loading: true,
      dialog: {
        visible: false,
        title: ''
      },
      show: true,
      page: {
        currentPage: 1,
        size: 10,
        total: 10
      },
      form: {
        username: '',
        name: '',
        gender: '',
        birthday: [],
        tel: '',
        address: '',
        status: null,
        email: ''
      },
      dialogForm: {
        username: '',
        name: '',
        gender: '',
        birthday: '',
        tel: '',
        address: '',
        status: false,
        email: '',
        roles: []
      },
      tableData: [],
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        roles: [
          { type: 'array', required: true, trigger: 'change', message: '角色不能为空' }
        ]
      },
      // 选中的值显示
      selectedList: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/api/system/user/importSysUser'
      },
      roles: []
    }
  },
  created() {
    this.loadList(this.page.currentPage, this.page.size)
  },
  methods: {
    loadList(currentPage, size) {
      this.loading = true
      UserApi.listSysUser(JSON.parse(JSON.stringify(this.form)), currentPage, size).then(res => {
        this.loading = false
        this.page.currentPage = res.data.currentPage
        this.page.size = res.data.size
        this.page.total = res.data.total
        this.tableData = res.data.records
      })
    },
    selectedChange(selectedList) {
      this.selectedList = JSON.parse(JSON.stringify(selectedList))
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.loadList(this.page.currentPage, val)
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.loadList(val, this.page.size)
    },
    handleDelete(data) {
      const ids = []
      if (data.id) {
        ids.push(data.id)
      } else {
        data.map(d => {
          ids.push(d.id)
        })
      }
      UserApi.delSysUser(ids).then(res => {
        this.$message.success('删除成功')
        this.loadList(this.page.currentPage, this.page.size)
      })
    },
    handleSearch() {
      this.loadList(this.page.currentPage, this.page.size)
      this.$message.success('查询成功')
    },
    handleClearSearch() {
      this.form = {
        username: '',
        name: '',
        gender: '',
        birthday: [],
        tel: '',
        address: '',
        status: null,
        email: ''
      }
    },
    handleOpenDialog(row) {
      RoleApi.getSysRole().then(res => {
        this.roles = res.data
      })
      this.dialog.visible = true
      if (row) {
        this.dialog.title = '修改'
        this.dialogForm = JSON.parse(JSON.stringify(row))
        console.log(this.dialogForm)
      } else {
        this.dialog.title = '新添'
      }
    },
    handleCloseDialog() {
      this.dialogForm = {
        username: '',
        name: '',
        gender: '',
        birthday: '',
        tel: '',
        address: '',
        status: false,
        email: '',
        roles: []
      }
      this.$refs.dialogForm.resetFields()
      this.dialog.visible = false
    },
    handleSubmit() {
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          const roles = []
          this.dialogForm.roles.map(r => {
            roles.push(r.id)
          })
          const user = JSON.parse(JSON.stringify(this.dialogForm))
          user.roles = roles
          if (user.id) {
            UserApi.updateSysUser(user).then(res => {
              this.$message.success('更新成功')
              this.handleCloseDialog()
              this.loadList(this.page.currentPage, this.page.size)
            })
          } else {
            UserApi.saveSysUser(user).then(res => {
              this.$message.success('添加成功')
              this.handleCloseDialog()
              this.loadList(this.page.currentPage, this.page.size)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleResetPassword':
          this.handleResetPassword(row)
          break
        case 'handleAssignRoles':
          this.handleAssignRoles(row)
          break
        default:
          break
      }
    },
    handleResetPassword(row) {
      UserApi.resetPassword(row.id).then(res => {
        this.$message.success('重置密码成功')
      })
    },
    handleAssignRoles(row) {},
    handleImportSysUser() {
      this.upload.title = '系统用户导入'
      this.upload.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + '成功：' + response.data.success + '失败：' + response.data.fail + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
      this.loadList(this.page.currentPage, this.page.size)
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    /** 下载模板操作 */
    importTemplate() {
      UserApi.exportSysUserTemplate().then(res => {
        upload(res, '系统用户导入模板.xlsx')
      })
    },
    handleExportSysUser() {
      UserApi.exportSysUser(this.form).then(res => {
        upload(res, '系统用户信息.xlsx')
      })
      this.$message.success('导出成功')
    },
    handleChangeStatus(data) {
      UserApi.changeStatus(data.id, data.status).then(res => {
        this.$message.success('更新成功')
        this.loadList(this.page.currentPage, this.page.size)
      })
    }
  }
}
</script>

<style scoped>
.g-row{
  margin-top: 10px;
}
.g-button{
  margin: 0;
  padding: 0;
  width: 40px
}
 .el-dropdown-link {
   cursor: pointer;
   color: #409EFF;
 }
.el-icon-arrow-down {
  font-size: 12px;
}
</style>
